/* 
 * Cashbox is the legal property of its developers, whose names are listed in the copyright file included
 * with this source distribution.
 * 
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU
 * General Public License as published by the Free Software Foundation; either version 2 of the License,
 * or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
 * Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this program; if not,
 * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

#import "CBTransferPanelController.h"
#import "CBCurrencyFormatter.h"

#import <Cashbox/CBAccount.h>
#import <Cashbox/CBAttributeInfo.h>
#import <Cashbox/CBDataControllerProtocol.h>

#define TO_STRING		FSLocalizedString(@"To Account", nil)
#define FROM_STRING		FSLocalizedString(@"From Account", nil)

static void *CBDirectionChangeContext = @"CBDirectionChangeContext";

@interface CBTransferPanelController (Private)
- (void)updateTransferTypes;
- (void)updateFilters;
@end

@implementation CBTransferPanelController

+ (NSString *)nibName {
	return @"TransferPanel";
}

- (void)awakeFromNib {
	[[amountTextField cell] setFormatter:[[[CBCurrencyFormatter alloc] init] autorelease]];
	
	[accounts setEntityName:[CBAccount entityName]];
	[accounts setManagedObjectContext:[[cashbox dataController] managedObjectContext]];
	[accounts setSortDescriptors:[NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease]]];
	[accounts fetchWithRequest:nil merge:NO error:NULL];
	
	[directions addObserver:self forKeyPath:@"selection" options:0 context:CBDirectionChangeContext];
	[self updateTransferTypes];
}

- (void)dealloc {
	[directions removeObserver:self forKeyPath:@"selection"];	
	[super dealloc];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
	if (context == CBDirectionChangeContext) {
		[self updateFilters];	
	}
}

- (void)updateTransferTypes {
	CBAttributeInfo *info = [[[[self account] class] transactionClass] attributeInfo];	
	[directions setContent:[NSMutableArray array]]; // clear
	if ([info attributeForRole:CBNegativeCashflowRole]) { [directions addObject:TO_STRING]; }
	if ([info attributeForRole:CBPositiveCashflowRole]) { [directions addObject:FROM_STRING]; }
	[directions setSelectionIndex:0];
}

- (void)updateFilters {
	CBTransferDirection direction = [self transferDirection];
	CBAttributeType type;
	if (direction == CBTransferTo) { type = CBPositiveCashflowRole; }
	else if (direction == CBTransferFrom) { type = CBNegativeCashflowRole; }
	[accounts setFilterPredicate:
	 [NSPredicate predicateWithFormat:
	  @"SELF != %@  && ANY class.transactionClass.attributeInfo.attributes.role == %@",
	  [self account],
	  [NSNumber numberWithUnsignedInt:type]]];
	[accounts rearrangeObjects];
	[accounts setSelectionIndex:0];
}

- (IBAction)finish:(id)sender {
	if (![self transferAccount]) {
		NSString *errorStr = FSLocalizedString(@"An account must be selected in order to create a transfer.", nil);
		NSDictionary *userInfoDict = [NSDictionary dictionaryWithObject:errorStr forKey:NSLocalizedDescriptionKey];
		NSError *error = [NSError errorWithDomain:@"CBTransferPanelDomain" code:0 userInfo:userInfoDict];
		[self presentError:error];		
	} else if (![self transferAmount]) {
		NSString *errorStr = FSLocalizedString(@"An amount must be entered in order to create a transfer.", nil);
		NSDictionary *userInfoDict = [NSDictionary dictionaryWithObject:errorStr forKey:NSLocalizedDescriptionKey];
		NSError *error = [NSError errorWithDomain:@"CBTransferPanelDomain" code:0 userInfo:userInfoDict];
		[self presentError:error];
	} else {
		[[self window] orderOut:nil];
		[NSApp endSheet:[self window] returnCode:NSAlertDefaultReturn];		
	}
}

- (IBAction)cancel:(id)sender {
	[[self window] orderOut:nil];
	[NSApp endSheet:[self window] returnCode:NSAlertAlternateReturn];
}


- (CBAccount *)transferAccount {
	return [[accounts selectedObjects] firstObject];
}

- (long long)transferAmount {
	return [[[NSValueTransformer valueTransformerForName:@"CBIntFloatTransformer"]
			 reverseTransformedValue:[amountTextField objectValue]] longLongValue];
}

- (CBTransferDirection)transferDirection {
	NSString *selection = [[directions selectedObjects] firstObject];
	if ([selection isEqualToString:TO_STRING]) {
		return CBTransferTo;
	} else if ([selection isEqualToString:FROM_STRING]) {
		return CBTransferFrom;		
	} else {
		return 0;
	}
}

- (CBAccount *)account {
	return account;
}

- (void)setAccount:(CBAccount *)acc {
	if (acc != account) {
		[account release];
		[self willChangeValueForKey:@"account"];
		account = [acc retain];
		[self didChangeValueForKey:@"account"];
	}	
}

- (void)didChangeValueForKey:(NSString *)key {
	if ([key isEqualToString:@"account"]) {
		[self updateTransferTypes];
		[self updateFilters];
	}
	[super didChangeValueForKey:key];
}

@end
